package com.zhouchao.mvp;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zhouchao.mvp.login.LoginContract;
import com.zhouchao.mvp.login.LoginPresenter;

public class LoginActivity extends AppCompatActivity implements LoginContract.ILoginView, View.OnClickListener{
    private static final String TAG = ">>>LoginActivity";
    private EditText etName;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnClear;
    private Dialog dialog;

    private LoginContract.ILoginPresenter loginPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        createPresenter();
    }

    private void init(){
        etName=findViewById(R.id.edit_name);
        etPassword=findViewById(R.id.edit_password);
        btnLogin=findViewById(R.id.btn_login);
        btnClear=findViewById(R.id.btn_clear);
        btnLogin.setOnClickListener(this);
        btnClear.setOnClickListener(this);
    }

    @Override
    public void createPresenter() {
        loginPresenter=new LoginPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loginPresenter.onDestroy();
    }

    @Override
    public String getName() {

        return etName.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString().trim();
    }

    @Override
    public void onClear() {
        etName.setText("");
        etPassword.setText("");
    }

    @Override
    public void onLoginSuccess() {
        startActivity(new Intent(this,MainActivity.class));
        finish();
    }

    @Override
    public void onLoginFailure(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgressBarVisibility(boolean show) {

        if(show){
            if(dialog==null){
                dialog=new Dialog(this);
                dialog.setContentView(R.layout.progress_circle);
                dialog.setCancelable(false);
            }
            if(!dialog.isShowing()){
                dialog.show();
            }
        }else{
            if(dialog!=null && dialog.isShowing()){
                dialog.dismiss();
            }
        }




    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_login:
                loginPresenter.login(getName(),getPassword());
                break;
            case  R.id.btn_clear:
                loginPresenter.clear();
                break;
        }
    }


}
